<template>
  <div>
    <el-form :inline="true" v-loading="loading" class="demo-form-inline">
      <el-row :gutter="0">
        <el-col :span="4">
          <el-form-item label="分类">
            <el-select
              v-model="categoryValue"
              placeholder="请选择"
              style="width: 120px"
            >
              <el-option
                v-for="item in options.category"
                :key="item.id"
                :label="item.category_name"
                :value="item.id"
                @click="test(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="时间">
            <el-date-picker
              v-model="dateValue"
              type="datetimerange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['12:00:00', '08:00:00']"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="关键字">
            <el-select
              v-model="search_key"
              placeholder="请选择"
              style="width: 80px"
            >
              <el-option
                v-for="item in searchOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="search_keywork"
            placeholder="请输入搜索内容"
            style="margin-left: -50px"
          ></el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="danger" style="margin-left: -30px" @click="getList"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button type="danger" @click="dialog_info = true">新增</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="black-30"></div>

    <!-- 表格数据 -->
    <el-table
      :data="tableData.item"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      >>
      <el-table-column type="selection" width="45"> </el-table-column>
      <el-table-column prop="title" label="标题" width="530"> </el-table-column>
      <el-table-column
        prop="categoryId"
        label="类别"
        width="130"
        :formatter="toCategory"
      >
      </el-table-column>
      <el-table-column
        prop="createDate"
        label="日期"
        width="237"
        :formatter="toDate"
      >
      </el-table-column>
      <el-table-column prop="user" label="管理员" width="115">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            @click="deleteItem(scope.row.id)"
            >删除</el-button
          >
          <el-button type="primary" size="small" @click="editInfo(scope.row.id)"
            >编辑</el-button
          >
          <router-link :to="{ name: 'InfoDetailed',query:{id:scope.row.id,title:scope.row.title}}">
            <!-- <el-button type="primary" size="small" class="ml10" @click="detailed(scope.row)">编辑详情</el-button> -->
            <el-button type="primary" size="small" class="ml10">编辑详情</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="black-30"></div>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-button type="danger" @click="deleteAll">批量删除</el-button>
      </el-col>
      <el-col :span="12">
        <el-pagination
          background
          layout="total,sizes,prev, pager, next,jumper"
          class="pull-right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 新增弹窗 -->
    <dialogInfo
      :flag.sync="dialog_info"
      @close="closeDialog"
      :category="options.category"
    />
    <!-- 修改弹窗 -->
    <dialogEditInfo
      :flag.sync="dialog_info_edit"
      @close="closeEditDialog"
      :category="options.category"
      :id="infoId"
      @getListEmit="getList"
    />
  </div>
</template>

<script setup>
import dialogInfo from "./dialog/info";
import dialogEditInfo from "./dialog/edit";
import { reactive, ref, onMounted } from "@vue/composition-api";
import { GetCategory, GetList, DeleteInfo } from "@/api/news";
import { timestampToTime } from "@/utils/common.js";
export default {
  name: "infoIndex",
  components: { dialogInfo, dialogEditInfo },
  setup(props, { root }) {
    // ref数据
    const dialog_info = ref(false);
    const dialog_info_edit = ref(false);
    const categoryValue = ref("");
    const dateValue = ref("");
    const search_key = ref("id");
    const search_keywork = ref("");
    const total = ref(0);
    const deleteInfoId = ref("");
    const infoId = ref("");
    //loading
    const loading = ref(false);
    // dialog对话框

    // 对象数据
    const options = reactive({
      category: [],
    });
    // 搜索关键字
    const searchOption = reactive([
      { value: "id", label: "ID" },
      { value: "title", label: "标题" },
    ]);

    //页码
    const page = reactive({
      pageNumber: 1,
      pageSize: 10,
    });

    //表格数据

    const tableData = reactive({
      item: [],
    });

    /**
     * 方法
     */
    const handleSizeChange = (val) => {
      page.pageSize = val;
      console.log(`每页 ${val} 条`);
    };

    const handleCurrentChange = (val) => {
      page.pageNumber = val;
      console.log(`当前页: ${val}`);
    };

    const closeDialog = () => {
      dialog_info.value = false;
    };

    const closeEditDialog = () => {
      dialog_info_edit.value = false;
    };

    /**
     * 搜索条件处理
     */
    const formatData = () => {
      let requestData = {
        pageNumber: page.pageNumber,
        pageSize: page.pageSize,
      };
      // 分类ID
      if (categoryValue.value) {
        requestData.categoryId = categoryValue.value;
      }
      // 日期
      if (dateValue.value.length > 0) {
        requestData.startTiem = dateValue.value[0];
        requestData.endTime = dateValue.value[1];
      }
      // 关键字
      if (search_keywork.value) {
        requestData[search_key.value] = search_keywork.value;
      }
      return requestData;
    };

    const editInfo = (id) => {
      console.log(id);
      dialog_info_edit.value = true;
      infoId.value = id;
    };

    // const detailed = (data) => {
      //第四种  在router.js中配置，在转跳页面用root.$router.params接收
      // root.$router.push({
      //   path:`/infoDetailed/${data.id}/${data.title}`
      // })
      // 第三种  params传值，params接收，
      // root.$router.push({
      //   name:'InfoDetailed',
      //   params:{
      //     id:data.row.id,
      //     title:data.row.title
      //   }
      // }

      //第二种
      // root.$router.push({
      //   name:'InfoDetailed',
      //   query:{
      //     id:data.row.id,
      //     title:data.row.title
      //   }
      // }
      // )}

    // const search = () => {
    //   let requestData = formatData()
    //   getList()
    //   // console.log(requestData);
    //   // getList()
    //   // console.log(categoryValue.value);
    //   // console.log(dateValue.value);
    //   // console.log(search_key.value);
    //   // console.log(search_keywork.value);
    // }
    // }
    const getList = () => {
      let requestData = formatData();
      // 加载状态
      loading.value = true;
      // let requestData = {
      //   categoryId: "",
      //   startTiem: "",
      //   endTime: "",
      //   title: "",
      //   id: "",
      //   pageNumber: page.pageNumber,
      //   pageSize: page.pageSize,
      // };
      GetList(requestData)
        .then((res) => {
          let data = res.data.data;
          //更新数据
          tableData.item = data.data;
          //页码统计数据
          total.value = data.total;

          console.log(tableData);
          loading.value = false;
        })
        .catch((err) => {
          console.log(err);
          loading.value = false;
        });
    };

    /**
     * 删除数据
     */
    const deleteItem = (id) => {
      deleteInfoId.value = [id];
      root.confirm({
        content: "确认删除当前信息？",
        tips: "警告",
        fn: confirmDelete,
        id: 111,
      });
    };

    const deleteAll = () => {
      if (!deleteInfoId.value || deleteInfoId.value.length == 0) {
        root.$message({
          message: "请选择删除数据",
          type: "error",
        });
        return false;
      }
      root.confirm({
        content: "确认删除全部信息？",
        fn: confirmDelete,
        id: "222",
      });
    };

    const confirmDelete = (value) => {
      DeleteInfo({ id: deleteInfoId.value })
        .then((res) => {
          console.log(res);
          deleteInfoId.value = "";
          getList();
        })
        .catch((err) => {
          console.log(err);
        });
    };

    // 获取分类
    const getCategory = () => {
      GetCategory({})
        .then((res) => {
          let data = res.data.data.data;
          console.log(data);
          options.category = data;
        })
        .catch((res) => {});
    };

    const getInfoCategory = () => {
      root.$store
        .dispatch("common/getInfoCategory")
        .then((res) => {
          console.log(res);
          options.category = res;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const toDate = (row) => {
      // console.log(row);
      return timestampToTime(row.createDate);
    };

    const toCategory = (row) => {
      console.log(row);
      console.log(options);
      let categoryId = row.categoryId;
      let categoryData = options.category.filter(
        (item) => item.id == categoryId
      )[0];
      return categoryData.category_name;
      console.log(aa);
    };

    const handleSelectionChange = (val) => {
      console.log(val);
      let id = val.map((item) => item.id);
      console.log(id);
    };

    onMounted(() => {
      // getCategory()
      //获取分类
      getInfoCategory();
      //获取列表
      getList();
    });

    const test = (item) => {
      console.log(item);
    };

    return {
      options,
      loading,
      deleteInfoId,
      infoId,
      categoryValue,
      dateValue,
      searchOption,
      search_key,
      formatData,
      search_keywork,
      total,
      tableData,
      handleCurrentChange,
      handleSizeChange,
      dialog_info,
      closeDialog,
      closeEditDialog,
      deleteItem,
      deleteAll,
      confirmDelete,
      getCategory,
      getInfoCategory,
      test,
      getList,
      toDate,
      toCategory,
      handleSelectionChange,
      dialog_info_edit,
      editInfo,
      // detailed
    };
  },
};
</script>

<style lang="scss" scoped>
.black-30 {
  height: 30px;
}
.ml10{
  margin-left: 10px;
}
</style>
